package com.wx.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wx.common.DateUtil;
import com.wx.common.JsonArrayResult;
import com.wx.common.JsonObjectResult;
import com.wx.common.redis.RedisUtil;
import com.wx.entity.WechatUserAddress;
import com.wx.service.UserAddressService;
import com.wx.service.UserService;

@RestController
@RequestMapping("/api")
public class UserAddressController {

	private static final Logger log = LoggerFactory.getLogger(UserAddressController.class);
	
	@Autowired
	private UserService userService;

	@Autowired
	private UserAddressService userAddressService;
	
	@Autowired
	private RedisUtil redis;
	
	@PostMapping("/template-msg/wxapp/formId")
	@ResponseBody
	public JsonObjectResult wxapp_formId(@RequestParam(value = "token") String token,
			@RequestParam(value = "type") String type, @RequestParam(value = "formId") String formId) {
		return new JsonObjectResult(0, null, "success");
	}

	/**
	 * 查询用户收货地址列表
	 * 
	 * @param token
	 * @return
	 */
	@GetMapping("/user/shipping-address/list")
	@ResponseBody
	public JsonArrayResult address_list(@RequestParam(value = "token") String token) {
		List<WechatUserAddress> list = new ArrayList<WechatUserAddress>();
		JsonArrayResult result = null;

		// 根据token查询用户id
		int id = userService.selectUidByToken(token);
		// 查询用户收货地址列表
		list = userAddressService.selectAllByUid(id);
		// 构建返回消息体
		result = new JsonArrayResult(JSONArray.parseArray(JSON.toJSONString(list)));

		return result;
	}

	/**
	 * 新增用户收货地址
	 * @param token
	 * @param provinceId 省份id
	 * @param cityId 城市id
	 * @param districtId 区域id
	 * @param linkMan 收货人姓名
	 * @param address 详细地址
	 * @param mobile
	 * @param code
	 * @param isDefault
	 * @return
	 */
	@PostMapping("/user/shipping-address/add")
	@ResponseBody
	public JsonObjectResult address_add(@RequestParam(value = "token") String token,
			@RequestParam(value = "provinceId") String provinceId,
			@RequestParam(value = "cityId") String cityId,
			@RequestParam(value = "districtId") String districtId,
			@RequestParam(value = "linkMan") String linkMan,
			@RequestParam(value = "address") String address,
			@RequestParam(value = "mobile") String mobile,
			@RequestParam(value = "code") String code,
			@RequestParam(value = "isDefault") boolean isDefault) {
		int uid = userService.selectUidByToken(token);
		String nowDate = DateUtil.getStringDate();
		
		WechatUserAddress insert = new WechatUserAddress();
		insert.setDateAdd(nowDate);
		insert.setDateUpdate(nowDate);
		insert.setUid(uid);
		insert.setProvinceId(provinceId);
		insert.setProvinceStr(redis.get("Address:" + provinceId));
		insert.setCityId(cityId);
		insert.setCityStr(redis.get("Address:" + cityId));
		insert.setDistrictId(districtId);
		insert.setAreaStr(redis.get("Address:" + districtId));
		insert.setAddress(address);
		insert.setCode(code);
		insert.setLinkMan(linkMan);
		insert.setMobile(mobile);
		insert.setStatus(0);
		insert.setStatusStr("正常");
		insert.setIsDefault(isDefault);
		userAddressService.insert(insert);
		
		userAddressService.updateIsDefault(insert.getId(), isDefault, uid);
		
		WechatUserAddress result = new WechatUserAddress();
		result.setAddress(address);
		result.setAreaStr(insert.getAreaStr());
		result.setCityId(cityId);
		result.setCityStr(insert.getCityStr());
		result.setCode(code);
		result.setDistrictId(districtId);
		result.setId(insert.getId());
		result.setIsDefault(isDefault);
		result.setLinkMan(linkMan);
		result.setMobile(mobile);
		result.setProvinceId(provinceId);
		result.setProvinceStr(insert.getProvinceStr());
		
		return new JsonObjectResult(0, JSONObject.parseObject(JSON.toJSONString(result)), "success");
	}
	
	/**
	 * 获取用户收货地址详情
	 * @param id
	 * @param token
	 * @return
	 */
	@GetMapping("/user/shipping-address/detail")
	@ResponseBody
	public JsonObjectResult address_detail(@RequestParam(value = "id") Integer id,
			@RequestParam(value = "token") String token) {
		int uid = userService.selectUidByToken(token);
		WechatUserAddress userAddressDetail = userAddressService.selectAddressByUidAndId(id, uid);

		return new JsonObjectResult(JSONObject.parseObject(JSON.toJSONString(userAddressDetail)));
	}
	
	/**
	 * 修改用户收货地址
	 * @param token
	 * @param provinceId
	 * @param cityId
	 * @param districtId
	 * @param linkMan
	 * @param address
	 * @param mobile
	 * @param code
	 * @param isDefault 是否为当前选择默认地址
	 * @return
	 */
	@PostMapping("/user/shipping-address/update")
	@ResponseBody
	public JsonObjectResult address_update(@RequestParam(value = "token") String token,
			@RequestParam(value = "id") Integer id,
			@RequestParam(value = "provinceId", required = false) String provinceId,
			@RequestParam(value = "cityId", required = false) String cityId,
			@RequestParam(value = "districtId", required = false) String districtId,
			@RequestParam(value = "linkMan", required = false) String linkMan,
			@RequestParam(value = "address", required = false) String address,
			@RequestParam(value = "mobile", required = false) String mobile,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "isDefault") boolean isDefault) {
		String nowDate = DateUtil.getStringDate();
		int uid = userService.selectUidByToken(token);
		
		if(provinceId == null) {
			try {
				userAddressService.updateIsDefault(id, isDefault, uid);
				return new JsonObjectResult(0, null, "success");
			} catch(Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
				return new JsonObjectResult(501, null, "system error");
			}
		}
		
		try {
			WechatUserAddress update = new WechatUserAddress();
			update.setId(id);
			update.setDateUpdate(nowDate);
			update.setProvinceId(provinceId);
			update.setProvinceStr(redis.get("Address:" + provinceId));
			update.setCityId(cityId);
			update.setCityStr(redis.get("Address:" + cityId));
			update.setDistrictId(districtId);
			update.setAreaStr(redis.get("Address:" + districtId));
			update.setAddress(address);
			update.setCode(code);
			update.setLinkMan(linkMan);
			update.setMobile(mobile);
			update.setIsDefault(isDefault);
			userAddressService.update(update);
			
			userAddressService.updateIsDefault(id, isDefault, uid);
			
			return new JsonObjectResult(0, null, "success");
		} catch(Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new JsonObjectResult(501, null, "system error");
		}
	}
	
	/**
	 * 删除用户收货地址
	 * @param token
	 * @param id
	 * @return
	 */
	@PostMapping("/user/shipping-address/delete")
	@ResponseBody
	public JsonObjectResult address_delete(@RequestParam(value = "token") String token,
			@RequestParam(value = "id") Integer id) {
		userAddressService.deleteByPrimaryKey(id);
		return new JsonObjectResult(0, null, "success");
	}
	
	/**
	 * 获得用户默认收货地址
	 * @param token
	 * @param id
	 * @return
	 */
	@GetMapping("/user/shipping-address/default")
	@ResponseBody
	public JsonObjectResult address_default(@RequestParam(value = "token") String token) {
		Integer uid = userService.selectUidByToken(token);
		if(uid == 0) {
			return new JsonObjectResult(1000, null, "token is false!");
		} else {
			WechatUserAddress address = userAddressService.selectDefaultAddressByUid(uid);
			if(address == null) {
				return new JsonObjectResult(700, null, "当前用户没有默认收货地址");
			}
			return new JsonObjectResult(JSONObject.parseObject(JSON.toJSONString(address)));
		}
		
	}

}
